import { getUserInfoApi, loginApi } from '@/api/user'
import router, { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { constantRoutes } from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {},
      routes: constantRoutes
    }
  },
  mutations: {
    // 1. 存token
    SET_TOKEN(state, token) {
      // 1.1 往本地存储token
      setToken(token)
      // 1.2 往state中存储token
      state.token = token
    },
    // 2. 删除token
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    // 3.设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    // 4.清空用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
    },
    SET_ROUTES(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }
  },
  actions: {
    // 1. 登录
    async login(context, { mobile, password }) {
      // todo
      const res = await loginApi({ mobile, password })
      context.commit('SET_TOKEN', res)
      Message.success('登陆成功')
      router.replace('/')
    },
    // 2. 退出登录
    async logout(context) {
      context.commit('REMOVE_TOKEN')
      context.commit('CLEAR_USER_INFO')
      // 清除路由数组
      resetRouter()
    },
    // 3.获取用户信息
    async getUserInfo(context) {
      const userInfo = await getUserInfoApi()
      context.commit('SET_USER_INFO', userInfo)
      console.log(userInfo)
      return userInfo // 返回数据
    }
  }
}

